package com.jerei.plugin.control;

import com.alibaba.fastjson.JSONObject;
import com.jerei.plugin.entity.WcmCommonResource;
import com.jerei.plugin.entity.WcmCommonResourceFolder;
import com.jerei.plugin.service.IWcmCommonResourceFolderService;
import com.jerei.plugin.service.IWcmCommonResourceService;
import com.jerei.utils.FileType;
import com.jerei.utils.UtilsCommon;
import com.jerei.utils.UtilsCondition;
import com.jerei.utils.UtilsImage;
import com.jerei.utils.spring.PageBean;
import com.jerei.web.plugin.controller.PluginController;
import com.jerei.web.utils.UtilsUI;
import com.jerei.web.utils.UtilsWeb;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import ro.fortsoft.pf4j.Extension;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by sunfeihu on 2016/10/21.
 */
@Extension
public class WcmCommonResourceControl extends PluginController {

    //业务逻辑层
    @Autowired
    private IWcmCommonResourceService iWcmCommonResourceService;

    @Autowired
    private IWcmCommonResourceFolderService iWcmCommonResourceFolderService;

    @RequiresPermissions({"common-resource:view"})
    public void list() {
        this.getModel().addAttribute("singleSelect", UtilsWeb.getString(this.getRequest(), "singleSelect"));
        this.getModel().addAttribute("fun", UtilsWeb.getString(this.getRequest(), "fun"));
    }


    /**
     * 百度编辑器上传
     *
     * @return
     */
    @RequiresPermissions({"common-resource:view"})
    public String ueditorUpload() throws IOException {
        JSONObject obj = new JSONObject();
        obj.put("state", "false");
        WcmCommonResource wcmCommonResource = this.doUpload(this.getRequest());
        if (null != wcmCommonResource) {
            obj.put("state", "SUCCESS");
            obj.put("original", wcmCommonResource.getOldFileName());
            obj.put("url", wcmCommonResource.getFilePath());
            obj.put("title", wcmCommonResource.getTitle());
        }
        return obj.toJSONString();
    }

    /**
     * 文件上传
     *
     * @param request 请求
     * @return 保存之后的资源文件对象
     */
    private WcmCommonResource doUpload(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multipartRequest.getFileNames();
        WcmCommonResource wcmCommonResource = null;
        MultipartFile file = null;
        String newName = null;
        FileType ft = null;
        String extName = null;
        String pFolder = null;
        String absPath = request.getSession().getServletContext().getRealPath("/");
        Long folderId = UtilsWeb.getLong(request, "folderId");
        while (iter.hasNext()) {
            file = multipartRequest.getFile((String) iter.next());
            if (file != null) {
                wcmCommonResource = new WcmCommonResource();
                UtilsWeb.setDefault(wcmCommonResource, request);
                wcmCommonResource.setFileSize(file.getSize() + "");
                extName = FilenameUtils.getExtension(file.getOriginalFilename());
                extName = extName.toLowerCase();
                newName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extName;
                ft = FileType.getFileType(extName);
                if (ft.equals(FileType.IMAGE)) {// 如果是图片
                    pFolder = "images";
                    wcmCommonResource.setFileType(1);
                } else if (ft.equals(FileType.MEDIA)) {// 如果是多媒体音视频
                    pFolder = "media";
                    wcmCommonResource.setFileType(2);
                } else if (ft.equals(FileType.FILE)) {// 如果是文件
                    pFolder = "file";
                    wcmCommonResource.setFileType(3);
                } else {// 如果是未知文件
                    return null;
                }
                wcmCommonResource.setOldFileName(file.getOriginalFilename());
                wcmCommonResource.setFileExtension(extName);
                wcmCommonResource.setFolderId(folderId);
                // 文件夹名称（年）
                String toFolder = File.separator + "upload" + File.separator + pFolder + File.separator + DateFormatUtils.format(Calendar.getInstance(), "yyyy") + File.separator;
                // 月
                toFolder += DateFormatUtils.format(Calendar.getInstance(), "MM") + File.separator;
                // 日
                toFolder += DateFormatUtils.format(Calendar.getInstance(), "dd");
                File folder = new File(absPath + toFolder);
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                File source = new File(absPath + toFolder + File.separator + newName);
                file.transferTo(source);
                wcmCommonResource.setFilePath(toFolder.replaceAll("\\\\", "/") + "/" + newName);
                if (ft.equals(FileType.IMAGE)) {// 如果是图片类型
                    // 压缩图片
                    String isResize = UtilsWeb.getString(request, "isResize");
                    if (!"false".equals(isResize)) {
                        UtilsImage.resize(source, 600);
                    }
                    JSONObject imgInfo = UtilsImage.getInfo(source);
                    wcmCommonResource.setFileSize(imgInfo.getLong("size") + "");
                    wcmCommonResource.setWidth(imgInfo.getInteger("width"));
                    wcmCommonResource.setHeight(imgInfo.getInteger("height"));

                    //生成中图
                    UtilsImage.resize(source, 300, "m");
                    wcmCommonResource.setFileMPath(UtilsCommon.getSmallImg(wcmCommonResource.getFilePath(), "m"));
                    //生成小图
                    UtilsImage.resize(source, 100, "s");
                    wcmCommonResource.setFileSPath(UtilsCommon.getSmallImg(wcmCommonResource.getFilePath(), "s"));
                }
                wcmCommonResource = iWcmCommonResourceService.save(wcmCommonResource);
                if (null != wcmCommonResource) {
                    return wcmCommonResource;
                }
            }
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @return 保存结果
     */
    @RequiresPermissions({"common-resource:view"})
    public String upload() throws IOException {
        WcmCommonResource wcmCommonResource = this.doUpload(this.getRequest());
        if (null != wcmCommonResource) {
            return UtilsUI.ok(wcmCommonResource);
        }
        return UtilsUI.fail();
    }

    /**
     * 数据删除
     *
     * @return 删除结果
     */
    @RequiresPermissions({"common-resource:remove"})
    public String delete() {
        String[] ids = this.getRequest().getParameterValues("ids");
        if (null != ids && ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                iWcmCommonResourceService.delete(UtilsCommon.getLong(ids[i]));
            }
        }

        return UtilsUI.ok();
    }

    /**
     * 匹配easyUI分页数据
     *
     * @return 分页格式数据
     */
    @RequiresPermissions({"common-resource:view"})
    public String page() {
        Integer nowPage = UtilsWeb.getInteger(this.getRequest(), "page");
        Integer pageSize = UtilsWeb.getInteger(this.getRequest(), "rows");
        PageBean<WcmCommonResource> pageBean = iWcmCommonResourceService.page(nowPage, pageSize, UtilsCondition.getConditionEntity(this.getRequest().getParameterMap()));
        return UtilsUI.datagrid(pageBean);
    }

    /**
     * 文件夹分页数据
     *
     * @return 分页数据
     */
    @RequiresPermissions({"common-resource:view"})
    public String folderPage() {
        Integer nowPage = UtilsWeb.getInteger(this.getRequest(), "page");
        Integer pageSize = UtilsWeb.getInteger(this.getRequest(), "rows");
        nowPage = 1;
        pageSize = 1000;
        PageBean<WcmCommonResourceFolder> pageBean = iWcmCommonResourceFolderService.page(nowPage, pageSize, UtilsCondition.getConditionEntity(this.getRequest().getParameterMap()));
        WcmCommonResourceFolder defaultFolder = new WcmCommonResourceFolder();
        defaultFolder.setName("未分类");
        if (null != pageBean.getResultList() && pageBean.getResultList().size() > 0) {
            pageBean.getResultList().set(0, defaultFolder);
        } else {
            List<WcmCommonResourceFolder> list = new ArrayList<WcmCommonResourceFolder>();
            list.add(defaultFolder);
            pageBean.setResultList(list);
        }
        return UtilsUI.datagrid(pageBean);
    }
}